package com.golxen.framework.db.dao;

import com.alibaba.fastjson.annotation.JSONField;
import com.golxen.framework.db.Option;

import java.util.concurrent.atomic.AtomicLong;

public abstract class AbstractDaoEntity {

    private short op = 0;

//	private long beginWriteTime = 0;
//	private long updateOptionTime;

    AtomicLong memoryMark = new AtomicLong();
    volatile long dbMark = 0;

    public synchronized void setOp(short option) {
        if (option == Option.Update) {// 记录更新时间
//			this.updateOptionTime = System.currentTimeMillis();
            memoryMark.incrementAndGet();
        }
        if ((this.op == Option.Insert) && (option == Option.Update)) {// 是插入状态，不允许更改为更新状态
            return;
        }
        if (option == Option.None) {// 设置为无状态
            // 如果写入记录不等于0 且更新记录大于写入记录，则说明记录了上次的写入记录后又有新增更新记录，而这次设置的是无状态，还要数据需要更新不允许设置为无状态
            if (dbMark != 0 && dbMark < memoryMark.get()) {
                this.op = Option.Update;
                return;
            }

//			if (beginWriteTime != 0 && updateOptionTime >= beginWriteTime) {
//				// 如果写入时间不等于0 且 更新时间大于准备写入时间，则说明需要重新更新，不允许设置为无状态
//				this.op = Option.Update;
//				return;
//			}
        }
        this.op = option;
    }

    public final short getOp() {
        return this.op;
    }

    public void initData() {
        setOp(Option.None);
    }

    public boolean isDirty() {
        return op == Option.Insert || op == Option.Update;
    }

    public boolean isUpdateOption() {
        return Option.Update == op;
    }

    public boolean isInsertOption() {
        return Option.Insert == op;
    }

    public void setUpdateOption() {
        setOp(Option.Update);
    }

    public void setNoneOption() {
        setOp(Option.None);
    }

    public void setInsertOption() {
        setOp(Option.Insert);
    }

    public void setBeginWriteTime() {
        this.dbMark = this.memoryMark.get();

//		this.beginWriteTime = System.currentTimeMillis();
    }

}
